using UnityEngine;
using System.Collections;

public class GameAnimation : MonoBehaviour 
{
	public int fps;
	float _fps;
	float timer;
	Texture2D[] textures;
	public string currentAnimation;
    private string animationMode;
	int currentTextures;
	bool playing = false;
	
	void Start () 
	{
        CalculateFps(1);
	}

    public void CalculateFps(int num)
    {
		if(num != fps)
		{
			fps = num;
	        _fps = 1.0f / fps;
			
			timer = 0;
		}
    }
	
	public void AddAnimation(Texture2D[] textures, string animationMode)
	{
		this.textures = textures;
        this.animationMode = animationMode;

		currentTextures = 0;
		gameObject.renderer.material.mainTexture = textures[0];
	}
	
	void Update () 
	{
		if(playing)
		{
			timer -= Time.deltaTime;
				
			if(timer <= 0)
			{
				NextFrame();
			}
		}
	}
	
	public void Play()
	{
		playing = true;
	}
	
	public void Stop()
	{
		playing = false;
        currentAnimation = "";
	}

	void NextFrame ()
	{
		if(currentTextures < textures.Length - 1)
		{
			currentTextures++;
		}
		else
		{
            if (animationMode == "OneShot")
            {
                Stop();
            }

            if (animationMode == "Loop")
            {
                currentTextures = 0;
            }
		}

		gameObject.renderer.material.mainTexture = textures[currentTextures];
		timer = _fps;
	}

    public bool isPlaying() { return playing; }
}
